#include "BoxPrimitiveSample.h"
#include "Application.h"
#include "utils.h"
#include "Utility.h"
#include "Texture.h"
#include "DiffuseLight.h"
#include "Metal.h"
#include "Translate.h"
#include "Rotate.h"
#include <thread>
namespace RayTracer
{
	void BoxPrimitiveSample::Init()
	{
		isGenerate = false;
		curIndex = 0;
		mImageParam = ImageParam(800, 500, "Box.png");
		lookfrom = vec3(0.0, 0.8, 1.0);
		lookat = vec3(0.0, 0.0, 0.0);
		fov = 60;
		upColor = vec3(0.5, 0.7, 1.0);
		downColor = vec3(1.0);
		groundColor = vec3(0.0);
		boxColor = vec3(1.0,0.0,0.0);
		bgColor = vec3(1.0);
		
		auto checker = std::make_shared<CheckerTexture>(vec3(0.2, 0.3, 0.1), vec3(0.9, 0.9, 0.9));
		auto noiseTexture = std::make_shared<NoiseTexture>(4);
		auto imageTexture = std::make_shared<ImageTexture>("../Resources/textures/wood.png");
		auto skyboxTexture = std::make_shared<ImageTexture>("../Resources/textures/skybox.jpg");

		auto lightMat = std::make_shared<Lambertian>(boxColor);
		auto floorMat = std::make_shared<Lambertian>(noiseTexture);
		auto skyboxMat = std::make_shared<Lambertian>(skyboxTexture);
		triangleMat = std::make_shared<Lambertian>(imageTexture);
		
		floor = std::make_shared<XZ_Rect>(-1, 1, -1, 1, -0 , floorMat);
		tri = std::make_shared<Triangle>(vec3(-1,0,0),vec3(-0.5,0.5,-0.3),vec3(0.0,0.0,-0.5),triangleMat);
		box = std::make_shared<Box>(vec3(-0.15,-0,-0.15),vec3(0.15,0.15,0.15), lightMat);
		box = std::make_shared<RotateY>(box,45);
		box = std::make_shared<Translate>(box,vec3(0.0,0.5,0.0));
		skybox = std::make_shared<Sphere>(vec3(0,0.5,0),0.5,skyboxMat); 
		world.add(skybox);
		world.add(floor);
		world.add(box);
		world.add(tri);
	}

	void BoxPrimitiveSample::Render()
	{
		int width = mImageParam.mWidth;
		int height = mImageParam.mHeight;
		camera = Camera(lookfrom, lookat, fov);

		uint8_t* pixels = new uint8_t[width * height * 3];
		int index = 0;
		for (int j = height - 1; j >= 0; j--) {
			for (int i = 0; i < width; ++i) {
				vec3 color = vec3(0.0f);
				for (int s = 0; s < samples_per_pixel; s++)
				{
					auto u = (i + Random01()) / (width - 1);
					auto v = (j + Random01()) / (height - 1);
					Ray r = camera.GetRay(u, v);
					color += RayColor(r , world, maxDepth);
				}
				auto scale = 1.0 / samples_per_pixel;
				color *= scale;

				GammaCorrect(color);
				pixels[index++] = static_cast<uint8_t>(256 * clamp(color.r, 0.0, 0.999));
				pixels[index++] = static_cast<uint8_t>(256 * clamp(color.g, 0.0, 0.999));
				pixels[index++] = static_cast<uint8_t>(256 * clamp(color.b, 0.0, 0.999));
				curIndex++;
			}
		}
		Utils::SaveImage(("Images/" + mImageParam.mName).c_str(), width, height, 3, pixels);
		isGenerate = true;
	}

	void BoxPrimitiveSample::ImGui()
	{
		ImGui::Text(u8"Rectangle Primitive");
		ImGui::Checkbox(u8"Normal", &isNormal);
		if (!isNormal)
		{
			ImGui::SliderInt(u8"Spp", &samples_per_pixel, 1, 500);
		}
		else
		{
			samples_per_pixel = 1;
		}
		ImGui::SliderInt(u8"MaxDepth", &maxDepth, 1, 50);
		ImGui::Separator();
		if (ImGui::CollapsingHeader(u8"Sky Color"))
		{
			ImGui::ColorEdit3(u8"Up SkyColor", &upColor[0]);
			ImGui::ColorEdit3(u8"Down SkyColor", &downColor[0]);
		}
		ImGui::Separator();
		if (ImGui::CollapsingHeader(u8"Camera"))
		{
			ImGui::InputFloat3(u8"Camera Position", &lookfrom[0]);
			ImGui::SliderFloat("Fov", &fov, 20.0, 180.0);
		}
		
		ImGui::Separator();
		auto w = (float)mImageParam.mWidth;
		auto h = (float)mImageParam.mHeight;
		auto progress = ((float)curIndex / (w * h));
		ImGui::ProgressBar(progress);
		if (ImGui::Button(u8"Generate")) {
			std::thread t = std::thread([=]() { Render(); });
			t.detach();
		}
		if (isGenerate) {
			auto mTexHandle = Utils::LoadTexture(("Images/" + mImageParam.mName).c_str());
			Application::GetInstance()->SetTexHandle(mTexHandle);
			isGenerate = false;
			curIndex = 0;
		}

	}

	void BoxPrimitiveSample::ShutDown()
	{
		Application::GetInstance()->SetTexHandle(0);
	}

	vec3 BoxPrimitiveSample::RayColor(const Ray& r, const Hitable& world, int depth)
	{
		HitRecord rec;
		if (depth <= 0) return vec3(0.0f);
		if (world.Hit(r, 0.001, infinity, rec))
		{
			vec3 res;
			if (isNormal)
			{
				res = 0.5f * (rec.normal + vec3(1.0f));
			}
			else
			{
				Ray scattered;
				vec3 attenuation;
				if (rec.matPtr->Scatter(r, rec, attenuation, scattered))
					return attenuation * RayColor(scattered, world, depth - 1);
				return vec3(1.0f);
			}
			return res;
		}

		vec3 unit_direction = glm::normalize(r.direction());
		auto t = 0.5f * (unit_direction.y + 1.0f);
		return (1.0f - t) * downColor + t * upColor;
	}

	vec3 BoxPrimitiveSample::RayColor(const Ray& r, const vec3& background, const Hitable& world, int depth)
	{
		HitRecord rec;

		if (depth <= 0)
			return vec3(0, 0, 0);

		if (!world.Hit(r, 0.001, infinity, rec))
			return background;

		Ray scattered;
		vec3 attenuation;
		vec3 emitted = rec.matPtr->Emitted(rec.u, rec.v, rec.position);

		if (!rec.matPtr->Scatter(r, rec, attenuation, scattered))
			return emitted;

		return emitted + attenuation * RayColor(scattered, background, world, depth - 1);
	}
}